/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.compomics.dataprovider.view.suite.panels.filetree;

import com.compomics.dataprovider.view.suite.model.FastaRepositoryProperties;
import com.compomics.dataprovider.view.suite.panels.filetable.FastaFileTable;
import java.io.File;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;

/**
 *
 * @author Kenneth
 */
public class FileTreeSelectionListener implements TreeSelectionListener {

    private final FastaFileTable table;
    private FastaFileTree tree;

    public FileTreeSelectionListener(FastaFileTable table) {
        this.table = table;
    }

    @Override
    public void valueChanged(TreeSelectionEvent e) {
        tree = (FastaFileTree) e.getSource();
        table.reset();
        try {
            for (TreePath aPath : tree.getSelectionPaths()) {
                String path = new File(FastaRepositoryProperties.getRepositoryPath()).getParentFile().getAbsolutePath();
                for (Object aPathObject : aPath.getPath()) {
                    path += "/" + aPathObject.toString();
                }
                File selectedFile = new File(path);
                if (!selectedFile.isDirectory()) {
                    table.addFile(selectedFile);
                }
            }
            table.update();
        } catch (NullPointerException ex) {
            //this happens if a file was (re)moved while building
            reset();
        }
    }

    private void reset() {
        if (tree != null) {
            tree.updateTree(new File(FastaRepositoryProperties.getRepositoryPath()));
        }
        table.reset();
        tree.setSelectionPath(new TreePath(tree.getModel().getRoot()));
    }

}
